import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // base address
  timeout: 10000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // inpouring token
    if (store.getters.token) {
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    // 判断是不是Blob
    if (response.data instanceof Blob) return response.data // 返回了Blob对象
    const { data, message, success } = response.data // default json mode
    if (success) {
      return data
    } else {
      Message({ type: 'error', message })
      return Promise.reject(new Error(message))
    }
  },
  async error => {
    if (error.response?.status === 401) {
      Message({ message: 'token超时了', type: 'warning' })
      // 说明token超时了
      await store.dispatch('user/logout') // 调用action 退出登录
      //  主动跳到登录页
      router.push('/login') // 跳转到登录页
      return Promise.reject(error)
    }
    // error.message
    Message.error(error.message)
    return Promise.reject(error)
  }
)

export default service
